package com.hexiang.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.validation.*;
import java.util.Set;

@Component
@Aspect
public class ValidAspect {

    //此处可以使用自定义注解，此处为扫描到service包的任何方法
    @Pointcut("execution(* *..*.service.*.*(..))")
    public void validPointCut() {
    }

    @Before("validPointCut()")
    public void doBefore(JoinPoint point) {
        Object[] args = point.getArgs();
        for (int i = 0; i < args.length; i++) {
            validate(args[i]);
        }
    }

    private void validate(Object o) {
        if (o == null){
            return;
        }
        ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
        Validator validator = vf.getValidator();
        //对参数进行校验，如果不满足条件，则将不满足条件的参数放到set中，此处可以自定义自己的异常将不满足的抛出
        Set<ConstraintViolation<Object>> set = validator.validate(o);
        for (ConstraintViolation<Object> constraintViolation : set) {
            throw new ConstraintViolationException(constraintViolation.getMessage(), set);
        }
    }
}
